package com.study.blog.exception;

import com.study.blog.common.result.BaseResponse;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public BaseResponse<String> returnExceptionError(Exception e) {
        System.out.println(e.getMessage());
        return BaseResponse.error(500, "服务器错误, 请与管理员联系");
    }

    @ResponseBody
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public BaseResponse<String> returnExceptionValidError(MethodArgumentNotValidException e) {

        BindingResult bindingResult = e.getBindingResult();

        List<String> list = new ArrayList<>();
        if (bindingResult.hasErrors()) {
            //获取到所有错误
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError error : fieldErrors) {
                String msg = error.getDefaultMessage();
                list.add(msg);
            }
        }
        return BaseResponse.error(500, String.join(", ", list));
    }
}
